<?php
/* The back-end functionality responsible for interfacing
   with TringMe APIs. It takes care of all the operations
   related to Login, Call and SMS.
   
   To know more about TringMe, visit http://tringme.com
   API and relevant details at http://tringme.com/developers.html
*/
include_once("tringmehelper.php");

define ("LOGINCOOKIE", "loginsession");
define ("HOSTNAME", "YOURHOSTNAME");

$gcookie="";
header('Content-type: text/javascript');

if(isset($_COOKIE[LOGINCOOKIE]) && $gcookie == "") {
	$gcookie = addslashes(trim($_COOKIE[LOGINCOOKIE]));
}

$op = GetRequestField('op','');

if($op=="login") {
	$logintype = 1;
	$email = GetRequestField('email', '');
	$password = GetRequestField('password', ''); 
	$left=GetRequestField('left');
	$top=GetRequestField('top');
	$phno=GetRequestField('phno');
	
	$vResult = false;
	if($email != '' && $password != '') {
		$vResult = TringMeLogin($email, $password, $gcookie);
	}
	
	if($vResult == true) {
		if(isset($_POST['remember'])) {
			$cookieresult = setcookie(LOGINCOOKIE, $gcookie, time()+3600*24*30);
		} else {
			$cookieresult = setcookie(LOGINCOOKIE, $gcookie);
		}
		 echo 'SetCookie("tringmeexloginsession","'.$gcookie.'","365");'; 
			
		echo 'ChangeBox('.$left.','.$top.',"'.$phno.'");';		
	}
	else {
		$msg = "Invalid Login";
		DisplayMessage($msg);
	}	
}
elseif($op=="get_cookie") {

	if($gcookie!="")
		echo 'SetCookie("tringmeexloginsession","'.$gcookie.'","365");';
		
}
elseif($op=="c2c") {
	
	$callsrc=GetRequestField('callsrc', '');
	$calldest=GetRequestField('calldest', '');
	if($gcookie!="") {
		if(TringMeClick2Call($callsrc,$calldest,$result,$gcookie)) 
			$msg = "Call is scheduled";
	  	else 
			$msg = "Call couldn't be placed";
	}
	else
		$msg = "Please login";
		
	DisplayMessage($msg);
}
elseif($op=="sms") {
	
	$calldest=GetRequestField('calldest', '');
	$msg=GetRequestField('msg', '');
	if($gcookie!="") {
		if(TringMeSendSMS($calldest,$msg,$result,$gcookie)) 
			$msg = "Message sent";
	  	else 
			$msg = "Message couldn't be send";
	}
	else {
		$msg = "Please login";
		echo 'SetCookie("tringmeexloginsession","'.$gcookie.'","365");'; 
	}
		
	DisplayMessage($msg);
}
elseif($op=="logout") {
	setcookie(LOGINCOOKIE, "", time()-3600*24, HOSTNAME);
	$gcookie = "";
}

function GetRequestField($field, $defaultval="") {
	$val = $defaultval;	
	if(isset($_REQUEST[$field])) {
		$val = addslashes(trim($_REQUEST[$field]));
	}
	return $val;
}

function DisplayMessage($msg) {
	echo 'document.getElementById("tr123message").innerHTML="'.$msg.'";';	
}

echo 'document.getElementsByTagName("head").item(0). removeChild(document.getElementById("server-resp"));';  
